import Page from "../../components/Page/Page"
import './Bulid.scss'
import { addBulid as _addBulid,getAllBulid,delBulid,editBulid} from '../../api/bulid'
import { useState,useEffect,useCallback,useRef } from 'react'
import { Button, Modal,Input,message} from 'antd';
const { confirm } = Modal;
import _ from 'lodash'

const Bulid = ()=>{
    const [bulidList,setBulidList] = useState([])
    const [total,setTotal] = useState(0)
    useEffect(()=>{
        getBulidList()
    },[])
    const getBulidList = useCallback(async()=>{
        const res = await getAllBulid({})
        setBulidList(res.data)
        setTotal(res.count)
    },[])
    const [isModalVisible, setIsModalVisible] = useState(false);
    const showAdd = useCallback(()=>setIsModalVisible(true),[]); 
    const cancelAdd = useCallback(()=>setIsModalVisible(false),[]); 
    const [bulidName,setBulidName] = useState('')
    const _setBulidName = _.debounce((val)=>{setBulidName(val.target.value)},500)
    const addBulid = async()=>{
        let res = await _addBulid({name:bulidName,floorInfo:[]})
        const { success } = res;
        if(!success) message.warning('添加失败');
        message.success('添加成功')
        getBulidList()
        cancelAdd()
    }

    const [curBulid,setCurBulid] = useState({})
    const [isModal, setIsModal] = useState(false);
    const showModal = () => {
        setIsModal(true);
    };
    const handleCancel = () => {
        setIsModal(false);
    };
    const del = async()=>{
        let res = await delBulid({bulidid:curBulid._id})
        const { success } = res;
        if(!success) message.warning('删除失败');
        message.success('删除成功')
        getBulidList()
        setIsModal(false);

    }

    const [showEditBox,setShowEditBox] = useState(false);
       const [editName,setEditName] = useState('') 
       useEffect(()=>{
        if(curBulid.name) setEditName(curBulid.name)
       },[curBulid])
       const handleEdit =async ()=>{
            let res = await editBulid({
                bulidid:curBulid._id,
                name: editName,
                floorInfo: curBulid.floorInfo
            })
            const { success } = res;
            if(!success) message.warning('刷新失败');
            message.success('刷新成功')
            getBulidList();
            setShowEditBox(false);
        }

        const fref = useRef(null)
        const addFloor = async()=>{
            const floorname = fref.current.value
            if(!floorname) return message.warning('楼层名称不能为空');
            const res =await editBulid({
                bulidid:curBulid._id,
                floorInfo:[
                    ...curBulid.floorInfo,
                    floorname
                ]
            })
            const { success } = res;
            if(!success) message.warning('添加失败');
            message.success('添加成功')
            getBulidList()
            fref.current.value = ''
            setCurBulid({
                ...curBulid,
                floorInfo:[
                    ...curBulid.floorInfo,
                    floorname
                ]
            })
        }

        const editFloor = async (index,ev)=>{
            const val = ev.target.previousElementSibling
            const newFloorInfo = curBulid.floorInfo;
            newFloorInfo[index] = val;
    
            const res = await editBulid({
                bulidid: curBulid._id,
                floorInfo: newFloorInfo,
            })
    
            const { success } = res;
            if(!success) message.warning('修改失败');
            message.success('修改成功')
            setCurBuld({
                ...curBulid,
                floorInfo:newFloorInfo
            })
        }
    return(
        <Page title='我是楼栋楼层'>
            <div className="howmuch">一共有 {total} 栋楼</div>
            <div className="bulidList">
                { 
                        bulidList.map(item=> (
                            <div 
                                key={item._id} 
                                onClick={ ()=>setCurBulid(item) }  
                                className={ item.name === curBulid.name ? 'ac':'' }
                            > 
                                 {item.name}
                            </div>
                        )) 
                }
                <Button type="primary" shape="round" onClick={showAdd}>添加楼栋</Button>
            </div>
            <div style={{marginTop:'30px'}}>
                楼栋名：{curBulid.name} 共 { curBulid.floorInfo?.length } 层 共有客房 : x 间

                <Button
                    type="primary"
                    style={{marginLeft:'15px'}}
                    onClick={()=>setShowEditBox(true)}
                >修改</Button>
                <Modal
                    title="修改楼栋"
                    cancelText="取消" 
                    okText="修改" 
                    visible={showEditBox} 
                    destroyOnClose
                    onCancel={()=>{
                        setShowEditBox(false)
                        setBulidName('')}}
                    onOk={handleEdit}
                >
                    <div>
                        <Input
                            placeholder="修改楼栋"
                            onChange={(val)=>setEditName(val.target.value)}
                            value={editName}
                        />
                    </div>
                </Modal>

                <Button 
                    type="primary" 
                    style={{marginLeft:'15px'}} 
                    onClick={showModal}
                >删除</Button>
                <Modal 
                    title="删除" 
                    visible={isModal} 
                    onOk={del} 
                    onCancel={handleCancel}
                    cancelText="取消" 
                    okText="确定" 
                >
                    <p>确定删除吗？</p>
                </Modal>
            </div>

            <div className="floorList"> 
               {
               curBulid.floorInfo?.map((item,index)=>(
                   <div key={item} onDoubleClick={ ev=>{
                    const cur = ev.currentTarget; //
                    cur.querySelector('.editbox').classList.toggle('hide')
                    cur.querySelector('div').classList.toggle('hide');
                    cur.querySelector('input').value = item;
                } }>
                       <div> {item} </div>
                       <div className="hide editbox">
                            <input type="text"/>
                            <button onClick={(ev)=>{
                                editFloor(index,ev)
                            }}>修改</button>
                            <button onClick={()=>{
                                delFloor(index)
                            }}>删除</button>
                       </div>
                   </div>
               ))
               }
               <div>
                   <input ref={fref} placeholder="请填写楼层名称"/>
                   <button onClick={addFloor}>立刻添加楼层</button>
               </div>
            </div>           

            <Modal
                title="添加楼栋"
                cancelText="取消" 
                okText="立即添加" 
                visible={isModalVisible} 
                destroyOnClose
                onCancel={()=>{
                    setIsModalVisible(false)
                    setBulidName('')}}
                onOk={addBulid}
            >
                <div>
                    <Input
                        placeholder="请输入楼栋名称"
                        onChange={(val)=>_setBulidName(val)}
                    />
                </div>
            </Modal>
        </Page>
    )
}
export default Bulid